$(function () {
    $('#link_reg').on('click', function () {
        $('.reg-box').show();
        $('.login-box').hide();
    })
    $('#link_login').on('click', function () {
        $('.reg-box').hide();
        $('.login-box').show();
    })

    var form = layui.form;
    form.verify({
        pwd: [
            /^[\S]{6,12}$/,
            '密码格式错误，必须是6-12位非空字符'
        ],
        repwd: function (value) {
            if (value != $('#form_reg [name=password]').val())
                return '两次密码不一致';
        }
    })
    var layer = layui.layer;

    $('#form_reg').on('submit', function (e) {
        e.preventDefault()
        // var data = {
        //     username: $('#form_reg [name=username]').val().trim(),
        //     password: $('#form_reg [name=password]').val().trim()
        // }
        var data = $(this).serialize()
        $.ajax({
            type: "post",
            url: "/api/reguser",
            data: data,
            success: function (response) {
                if (response.status !== 0) {
                    return layer.msg(response.message, {
                        icon: 5,
                        time: 1000 //1秒关闭（如果不配置，默认是3秒）
                    });
                }
                layer.msg(response.message, {
                    icon: 6,
                    time: 1000
                }, function () {
                    $('#link_login').click();
                })
            }
        })
    })
    $('#form_login').on('submit', function (e) {
        e.preventDefault()
        var data = $(this).serialize()
        $.ajax({
            type: "post",
            url: "/api/login",
            data: data,
            success: function (response) {
                if (response.status !== 0) {
                    return layer.msg(response.message, {
                        icon: 5,
                        time: 1000
                    });
                }
                localStorage.setItem('token', response.token)
                location.href = 'index.html';
            }
        })
    })
})